package cn.qayy.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.qayy.dao.PolicyLogMapper;
import cn.qayy.dao.PolicyMapper;
import cn.qayy.dto.PolicyLogDTO;
import cn.qayy.po.Policy;
import cn.qayy.po.PolicyLog;
import cn.qayy.po.User;
import cn.qayy.service.IPolicyLogService;
import cn.qayy.utils.BeanToMapUtils;
import cn.qayy.utils.DownLoadUtil;

/***
 * @author wangyu
 *
 */
@Service("policyLogServiceImpl")
public class PolicyLogServiceImpl implements IPolicyLogService {

	@Resource
	private PolicyLogMapper policyLogMapper;
	
	@Resource
	private PolicyMapper policyMapper;
	
	@Override
	public PageInfo<PolicyLog> selectPolicyLogBy(PolicyLogDTO dto) throws Exception {
		if (dto != null) {
			DownLoadUtil.set("PolicyLogDTO",dto);
			List<PolicyLog> list = policyLogMapper.selectPolicyLogBy(dto);
			Integer policyId = Integer.valueOf(dto.getId());
			Policy policy = policyMapper.selectByPrimaryKey(policyId);
			if(policy!=null) {
				PolicyLog log = new PolicyLog();
				log = log.setByPolicy(policy);
				list.add(log);
			}
			PageHelper.startPage(dto.getPageNumber(), dto.getPageSize());
			PageInfo<PolicyLog> pageInfo = new PageInfo<PolicyLog>(list);
			return pageInfo;
		}
		return null;
	}

	@Override
	public int insertByList(List<Policy> list,HttpServletRequest request) {
		String logAction = (String) request.getAttribute("logAction");
		User user = (User)request.getSession().getAttribute("user");
		List<PolicyLog> policylog = new ArrayList<PolicyLog>();
		List<Policy> policylist = policyMapper.selectBeforeByIds(list);
		for(Policy policy :policylist) {
			PolicyLog log = new PolicyLog();
			log = log.setByPolicy(policy);
			log.setLogDataer(user.getUser_name());
			log.setLogTime(new Date().toString());
			log.setLogType(logAction);
			policylog.add(log);
		}
		return policyLogMapper.insertByList(policylog);
	}
	
	public List<Map<String, Object>> selectListByDown(PolicyLogDTO dto){
		List<Map<String, Object>> retList = new ArrayList<Map<String, Object>>();
		try {
			List<PolicyLog> list = policyLogMapper.selectPolicyLogBy(dto);
			
			Integer policyId = Integer.valueOf(dto.getId());
			Policy policy = policyMapper.selectByPrimaryKey(policyId);
			if(policy!=null) {
				PolicyLog log = new PolicyLog();
				log = log.setByPolicy(policy);
				list.add(log);
			}
			
			//把对象集合转为Map
			for(PolicyLog log : list) {
				Map<String, Object> map;
				map = BeanToMapUtils.objectToMap(log);
				retList.add(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retList;
	}


}
